<?php

namespace app\model\v1;

use app\BaseModel;
use think\exception\HttpException;
use think\exception\ValidateException;

// 角色
class Role extends BaseModel
{
    /**
     * 获取角色列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(): array
    {
        $roleList = $this->select()->toArray();
        $authModel = new Auth();
        $roles = [];
        foreach ($roleList as $key => $val) {
            $val['auths'] = [];
            $authList = $authModel->whereIn('id', $val['auth_ids'])->select()->toArray();
            foreach ($authList as $k => $v) {
                $val['auths'][$k]['names'] = $v['menu_title'];
                $val['auths'][$k]['actions'] = $v['actions'];
            }
            $roles[] = $val;
        }
        return $roles;
    }

    /**
     * 角色信息
     * @param int $id
     * @return array|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(int $id) {
        $roleInfo = $this->find($id);
        if (!$roleInfo) {
            throw new HttpException(404, '角色信息不存在');
        }
        return $roleInfo;
    }

    /**
     * 新增角色
     * @param array $postForm
     * @return bool
     */
    public function add(array $postForm): bool
    {
        return $this->save($postForm);
    }

    /**
     * 角色修改
     * @param array $postForm
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(array $postForm): bool
    {
        $role = $this->find($postForm['id']);
        if ($role->getAttr('is_super') == 1) {
            throw new ValidateException('超级管理员不能修改');
        }
        return $role->save($postForm);
    }

    /**
     * 角色删除
     * @param int $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del(int $id): bool
    {
        $role = $this->find($id);
        if ($role->getAttr('is_super') == 1) {
            throw new ValidateException('超级管理员不能删除');
        }
        return $role->delete();
    }

}